/**
 * 一些通用方法
 */
(function (exports) {
    /**
     * 
     * @param {string} dom 目标dom元素
     * @param {string} className  效果的class
     */
    exports.tabEffect = function (dom, className) {
        // if (typeof dom === 'string') {
        //     dom = document.querySelector(dom);
        // }
        $("body").on("click", dom, function () {
            var index = $(this).index();
            $(dom).removeClass(className).eq(index).addClass(className);
        })

    }
    /**
     * 将对象渲染到模板
     * @param {String} template 对应的目标
     * @param {Object} obj 目标对象
     * @return {String} 渲染后的模板
     */
    exports.renderTemplate = function (template, obj) {
        return template.replace(/[{]{2}([^}]+)[}]{2}/g, function ($0, $1) {
            return obj[$1] || '';
        });
    };

    /**
     * 
     * 截取url参数
     */

    exports.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }


    /**
     * 
     * 下载护士加
     */
    exports.authUrl = function (itemId, param) {
        // window.location.href="http://h5game.tuyoo.com/?act=game.init&itemId="+itemId+"&param="+param;

    };


    /**
     *
     *
     * @param {*} url 请求url
     * @param {*} requestData  请求参数
     * @param {*} callback 回调函数
     */
    exports.getData = function (url, requestData, callback) {
        $.post(url, requestData, function (data) {
            if (data.retcode == -2) {
                $(".tipBox").hide();
                $("#noUser").show();
            } else {
                callback(data);
            }
        }, "json");
    }
    /**
     * 绑定监听事件 暂时先用click
     * @param {String} dom 单个dom,或者selector
     * @param {Function} callback 回调函数
     * @param {String} eventName 事件名
     */
    exports.bindEvent = function (dom, callback, eventName) {
        eventName = eventName || 'click';
        if (typeof dom === 'string') {
            // 选择
            dom = document.querySelectorAll(dom);
        }
        if (!dom) {
            return;
        }
        if (dom.length > 0) {
            for (var i = 0, len = dom.length; i < len; i++) {
                dom[i].addEventListener(eventName, callback);
            }
        } else {
            dom.addEventListener(eventName, callback);
        }
    };
    /**
     * @return {boolean}
     */
    exports.IsNull = function (v) {
        return v === undefined || v === null || v === "";
    };
    /**
     *
     *
     * @param {*} url 请求url
     * @param {*} requestData  请求参数
     * @param {*} callback 回调函数
     */
    exports.getData = function (url, requestData, callback) {
        $.get(url, requestData, function (data) {
            if (data.retcode == 0) {
                alert("shibai");
            } else {
                callback(data);
            }
        }, "json");
    }

    /**
     * 
     * 判断是否为微信设备
     * 
     */

    exports.checkIsWeixin = function () {
        if (!window.nurse) {
            window.nurse = new Object;
        }
        var u = navigator.userAgent,
            app = navigator.appVersion;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        var isWeixin = !!u.match(/MicroMessenger/i); //weixin
        if (isWeixin) {
            return true;
        }
        return false;
    }


    /**
     * 微信分享
     * @param {string} shareTitle1 分享朋友圈title
     * @param {string} shareTitle2 分享朋友title
     * @param {string} shareContent 分享内容
     * @param {string} shareUrl   分享页面的url
     * @param {string} shareImg1  分享到朋友圈图标
     * @param {string} shareImg2  分享到朋友的图标
     */
    exports.getConfig = function (shareTitle1, shareTitle2, shareContent, shareUrl, shareImg1, shareImg2) {
        // 获取分享配置信息
        var urlC = window.location.href.split('#')[0];
        $.ajax({
            url: "http://h5game.tuyoo.com/?act=ajax.getWxSign",
            type: 'GET',
            dataType: 'json',
            data: {
                'url': urlC
            },
            success: function (data) {
                var data = data.signPackage;
                if (data.appId == 0) {
                    console.log('获取分享配置信息失败');
                } else {
                    wx.config({
                        debug: false,
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.nonceStr,
                        signature: data.signature,
                        jsApiList: [
                            'checkJsApi',
                            'onMenuShareTimeline',
                            'onMenuShareAppMessage',
                            'hideMenuItems'
                        ]
                    });
                    wx.ready(function () {
                        wx.checkJsApi({
                            jsApiList: [
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                'hideMenuItems'
                            ],
                            success: function (res) {
                                console.log('微信配置成功' + JSON.stringify(res));
                            },
                            fail: function (res) {
                                console.log(JSON.stringify(res));
                            }
                        });
                        wx.hideMenuItems({
                            menuList: [
                                'menuItem:share:timeline',
                                'menuItem:readMode', // 阅读模式
                                "menuItem:share:qq", //分享到qq
                                "menuItem:share:weiboApp", //分享到微博
                                "menuItem:openWithQQBrowser", //qq浏览器打开
                                "menuItem:openWithSafari", //safri打开
                                "menuItem:share:QZone", //空间
                                'menuItem:copyUrl' //复制链接
                            ],
                            success: function (res) {
                                console.log('已隐藏“阅读模式”，“分享到朋友圈”，“复制链接”等按钮');
                            },
                            fail: function (res) {
                                console.log(JSON.stringify(res));
                            }

                        });
                        wx.onMenuShareAppMessage({
                            title: shareTitle2,
                            desc: shareContent,
                            link: shareUrl,
                            imgUrl: shareImg2,
                            success: function () {
                                console.log("朋友成功");
                            },
                            cancel: function () {},
                            fail: function (res) {}
                        });
                        wx.onMenuShareTimeline({
                            title: shareTitle1,
                            link: shareUrl,
                            imgUrl: shareImg1,
                            success: function () {
                                console.log("分享到朋友圈成功");
                            },
                            cancel: function () {},
                            fail: function (res) {
                                console.log("朋友圈失败--" + JSON.stringify(res));
                            }
                        });
                    });
                    wx.error(function (res) {
                        console.log('微信分享错误' + res.errMsg);
                    });
                }
            },
            error: function (data) {
                console.log(data);
            }
        })
    }



    /**
     * 
     * 微信支付接口
     * @param {string} par1 分享朋友圈title
     * @param {string} par2 
     * @param {fn} callback 回调函数
     */

    exports.wxPay = function (par1, par2, callback) {

        $.ajax({
            // url: "/?act=voucher.commonwxpay&from=tyddz&vouch_user_id=" + user_id + "&prod_id=" + prod_id,
            processData: true,
            dataType: 'json',
            success: function (r) {
                console.log(r);
                if (r.code != '200') {
                    alert(r.msg);
                    return;
                } else {
                    var param = r.jsapi;
                    if (param == null) {
                        alert("接口返回错误，请联系客服！")
                        return false;
                    }
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId": param.appId,
                            "timeStamp": param.timeStamp,
                            "nonceStr": param.nonceStr,
                            "package": param.package,
                            "signType": "MD5",
                            "paySign": param.sign
                        },
                        function (res) {
                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                //发送微信消息
                                localStorage.ddzuserId = user_id;
                                localStorage.ddzimgUrl = imgUrl;
                                localStorage.ddznickName = nickName;
                                if (flag == 1) {
                                    $(".liuyuan").hide();
                                }
                            } else {
                                if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                    alert("您已取消支付。");
                                } else {
                                    alert('充值失败，请稍后再试。');

                                }
                            }
                        }
                    );
                }
            },
            error: function (info) {
                alert(JSON.stringify(info));
            }
        });

    };
    /**
     * 
     * @param {*} DomId 拖拽的dom
     */

    exports.dragFn = function (DomId) {
        var timer;

        function timeOpen() {
            timer = setInterval(function () {
                //			$("#dragBox").addClass("twink");
                var left = document.getElementById("dragBox").offsetLeft;
                if (left == 0) {
                    var moveL = left + 5;
                    var origL = left;
                    var timer1 = setInterval(function () {
                        $("#dragBox").animate({
                            "left": moveL + "px"
                        }, 100, function () {
                            $("#dragBox").animate({
                                "left": origL + "px"
                            }, 100)
                        })
                    }, 200)
                    setTimeout(function () {
                        clearInterval(timer1);
                    }, 600)
                } else {
                    var moveL = left - 5;
                    var origL = left;
                    var timer1 = setInterval(function () {
                        $("#dragBox").animate({
                            "left": moveL + "px"
                        }, 100, function () {
                            $("#dragBox").animate({
                                "left": origL + "px"
                            }, 100)
                        })
                    }, 200)
                    setTimeout(function () {
                        clearInterval(timer1);
                    }, 600)
                }
            }, 3000)
        }

        function closeTimer() {
            clearInterval(timer);
            timer = null;
        }

        var getCss = function (o, key) {
            return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
        };
        var offsetH = document.getElementById(DomId).offsetTop;
        var offsetW = document.getElementById(DomId).offsetLeft;
        var clientW = document.documentElement.clientWidth;
        var clientH = document.documentElement.clientHeight;
        var boxW = document.getElementById(DomId).offsetWidth;
        var boxH = document.getElementById(DomId).offsetHeight;

        function drag(element) {
            element.style.top = getCss(element, "top");
            element.style.left = getCss(element, "left");
            timeOpen();
            var hammer = new Hammer(element); //hammer实例
            var x = 0;
            var y = 0;
            hammer.on('panstart', function (event) {
                closeTimer();
                x = parseInt(element.style.left);
                y = parseInt(element.style.top);
                console.log(x);
            });
            hammer.on('panmove', function (event) {
                var ypx = y + event.deltaY;
                var xpx = x + event.deltaX;
                element.style.top = ypx + "px";
                element.style.left = xpx + "px";
                if (xpx <= 0) {
                    element.style.left = "0px"
                }
                if ((clientW - xpx - boxW) <= 0) {
                    element.style.left = (clientW - boxW) + "px"
                }
                if (ypx <= 0) {
                    element.style.top = "0px"
                }
                if ((clientH - ypx - boxH) <= 0) {
                    element.style.top = (clientH - boxH) + "px"
                }
            });
            hammer.on('panend', function (event) {
                var bodyWidth = document.documentElement.clientWidth;
                var dleft = element.offsetLeft;
                if (dleft < (bodyWidth / 2)) {
                    dleft = 0;
                } else {
                    dleft = (bodyWidth - element.offsetWidth);
                }
                element.style.left = dleft + "px";
                timeOpen();
            });
        }
        var myElement = document.getElementById(DomId);
        drag(myElement);
    }



})(window.GameCenter = {});